//图片上传预览    IE是用了滤镜。


// preview
function previewImage(file,type) {
    var MAXWIDTH = 260;
    var MAXHEIGHT = 180;

    if (file.files && file.files[0]) {
        var img;
        var div;
        if(type==1){
            div = document.getElementById('preview1')
            div.innerHTML = '<img id=defaultImg1>';
            img = document.getElementById('defaultImg1');
        }else if(type==2){
            div = document.getElementById('preview2')
            div.innerHTML = '<img id=defaultImg2>';
            img = document.getElementById('defaultImg2');
        }
        img.onload = function () {
            var rect = clacImgZoomParam(MAXWIDTH, MAXHEIGHT, img.offsetWidth, img.offsetHeight);
            img.width = rect.width;
            img.height = rect.height;
            // img.style.marginLeft = rect.left+'px';
            //img.style.marginTop = rect.top+'px';
        }
        var reader = new FileReader();
        reader.onload = function (evt) {
            img.src = evt.target.result;
            upLoadImg(evt.target.result, type, 2);
        }
        reader.readAsDataURL(file.files[0]);
    }
}


/**
 *
 * @param {Object} image  图片名字
 * @param {Object} type   图片类型
 * @param {Object} index  图片序号
 */
function upLoadImg(image, type, index) {
    $.ajax({
        url: urlcore + "/api/attachment/saveFile",
        type: "post",
        dataType: 'json',
        contentType: "application/json;charset=utf-8",
        data: JSON.stringify({
            "base64": image
        }),
        processData: false,
        success: function (data) {
            if (data.success == true) {
                var da = data.data;

                if (type == 1) {
                    $("#identityFront").val(da);
                }else if(type==2){
                    $("#identityBack").val(da);
                }
            } else {
                alert(data.msg)
            }
        },
        error: function () {
            /*alert("error");*/
        }
    });
}

//预览图片尺寸
function clacImgZoomParam(maxWidth, maxHeight, width, height) {
    var param = {top: 0, left: 0, width: width, height: height};
    if (width > maxWidth || height > maxHeight) {
        rateWidth = width / maxWidth;
        rateHeight = height / maxHeight;

        if (rateWidth > rateHeight) {
            param.width = maxWidth;
            param.height = Math.round(height / rateWidth);
        } else {
            param.width = Math.round(width / rateHeight);
            param.height = maxHeight;
        }
    }

    param.left = Math.round((maxWidth - param.width) / 2);
    param.top = Math.round((maxHeight - param.height) / 2);
    return param;
}
